<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import type { Customer } from "@/utils/types";
import axios from 'axios'
import Alert from '../components/Alert.vue'
import { useRoute } from 'vue-router';
const route = useRoute()
// const router = useRouter()


const customers = ref<Customer[]>([])
const alert = ref<string>("")
const filterInput = ref<string>("")


if (route.query.alert) {
  alert.value = String(route.query.alert)  // 类型强制转化

  setTimeout(() => {
    alert.value = "";
  }, 2000)
}






onMounted(async () => {
  const res = await axios.get('http://localhost:3000/users')
  // console.log(res.data);
  customers.value = res.data
})

// 在现有的数据中进行过滤
const filterBy = (customers: Customer[], value: string) => {
  return customers.filter((customer: Customer) => customer.name.match(value))
}




</script>

<template>

  <!-- container两边留白 -->
  <div class="home container">
    <Alert v-if="alert" :message="alert" />

    <input type="text" class="form-control" placeholder="请输入" v-model="filterInput" />
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">姓名</th>
          <th scope="col">电话</th>
          <th scope="col">邮箱</th>
          <th scope="col"></th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="customer in filterBy(customers,filterInput)" :key="customer.id">
          <th scope="row">{{customer.id}}</th>
          <td>{{customer.name}}</td>
          <td>{{customer.phone}}</td>
          <td>{{customer.email}}</td>
          <td>
            <router-link class="btn btn-warning" :to="'/details/'+customer.id">详情</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
